package com.orderVideo.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orderVideo.entity.Order;
import com.orderVideo.entity.User;
import com.orderVideo.enums.OrderQueryType;
import com.orderVideo.mapper.OrderMapper;
import com.orderVideo.service.OrderService;
import com.orderVideo.service.UserService;
import com.orderVideo.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
* @author Sakur
* @description 针对表【order(订单表)】的数据库操作Service实现
* @createDate 2025-03-27 14:43:47
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{

    @Autowired
    private UserService userService;

    @Override
    public Order createOrder(Order requestOrder) {
        if (requestOrder.getUserId() == null) {
            requestOrder.setUserId(LoginUser.getUserId());
        }
        requestOrder.setOrderStatus(1);
        requestOrder.setOrderTime(LocalDateTime.now());
        this.save(requestOrder);
        return requestOrder;
    }

    @Override
    public boolean updateOrderStatus(Long orderId, Integer status) {
        Order order = this.getById(orderId);
        if (order == null) {
            return false;
        }
        order.setOrderStatus(status);
        return this.updateById(order);
    }

    @Override
    public Order getOrderById(Long orderId) {
        return this.getById(orderId);
    }

    @Override
    public List<Order> queryOrders(Long userId, OrderQueryType queryType) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId);
        
        // 根据查询类型设置时间范围
        setTimeRange(wrapper, queryType);
        
        return this.list(wrapper);
    }

    @Override
    public IPage<Order> queryOrdersPage(Long userId, Long page, Long size, OrderQueryType queryType) {
        IPage<Order> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId);
        wrapper.orderByDesc(Order::getOrderTime);
        // 根据查询类型设置时间范围
        setTimeRange(wrapper, queryType);
        
        return this.page(pageParam, wrapper);
    }

    @Override
    public IPage<Order> queryOrdersPage(Long page, Long size, OrderQueryType queryType) {
        IPage<Order> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        // 根据查询类型设置时间范围
        setTimeRange(wrapper, queryType);
        return baseMapper.selectPage(pageParam, wrapper);
    }

    @Override
    public boolean deleteOrder(Long orderId) {
        return this.removeById(orderId);
    }

    @Override
    public BigDecimal calculateUserTotalAmount(Long userId) {
        // 查询用户所有已完成的订单
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId)
               .eq(Order::getOrderStatus, 2); // 假设 status=2 表示已完成订单
        
        List<Order> completedOrders = this.list(wrapper);
        // 计算总金额
        return completedOrders.stream()
                .map(Order::getOrderMoney)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    @Override
    public BigDecimal calculateUserTodayEarnings(Long userId) {
        DateTime now = DateUtil.date();
        DateTime startTime;
        DateTime endTime;
        // 获取今天的开始时间和结束时间
        startTime = DateUtil.beginOfDay(now);
        endTime = DateUtil.endOfDay(now);
        // 查询今日已完成的订单
        List<Order> todayOrders = this.lambdaQuery()
                .eq(Order::getUserId, userId)
                .eq(Order::getOrderStatus, 2) // 已完成的订单
                .between(Order::getOrderTime, startTime, endTime)
                .list();

        // 计算今日收益总额
        return todayOrders.stream()
                .map(Order::getOrderMoney)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 根据查询类型设置时间范围
     */
    private void setTimeRange(LambdaQueryWrapper<Order> wrapper, OrderQueryType queryType) {
        if (queryType == null) {
            return;
        }

        DateTime now = DateUtil.date();
        DateTime startTime;
        DateTime endTime;

        switch (queryType) {
            case TODAY:
                startTime = DateUtil.beginOfDay(now);
                endTime = DateUtil.endOfDay(now);
                break;
            case THIS_WEEK:
                startTime = DateUtil.beginOfWeek(now);
                endTime = DateUtil.endOfWeek(now);
                break;
            case THIS_MONTH:
                startTime = DateUtil.beginOfMonth(now);
                endTime = DateUtil.endOfMonth(now);
                break;
            default:
                return;
        }
        // 格式化为yyyy-MM-dd HH:mm:ss格式
        String formattedStartTime = DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss");
        String formattedEndTime = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:ss");
        wrapper.between(Order::getOrderTime, formattedStartTime, formattedEndTime);
    }

    @Override
    @Transactional
    public boolean updateOrder(Order order) {
        // 获取原订单信息
        Order oldOrder = getById(order.getOrderId());
        if (oldOrder == null) {
            throw new RuntimeException("订单不存在");
        }

        // 如果订单状态由非完成变为完成状态，增加用户余额
        if (oldOrder.getOrderStatus() != 1 && order.getOrderStatus() == 1) {
            User user = userService.getById(order.getUserId());
            if (user != null && order.getOrderMoney() != null) {
                // 增加用户余额
                BigDecimal newUserMoney = user.getUserMoney().add(order.getOrderMoney());
                user.setUserMoney(newUserMoney);
                userService.updateById(user);
            }
        } 
        // 如果订单状态由完成变为非完成状态，减少用户余额
        else if (oldOrder.getOrderStatus() == 1 && order.getOrderStatus() != 1) {
            User user = userService.getById(order.getUserId());
            if (user != null && oldOrder.getOrderMoney() != null) {
                // 减少用户余额
                BigDecimal newUserMoney = user.getUserMoney().subtract(oldOrder.getOrderMoney());
                user.setUserMoney(newUserMoney);
                userService.updateById(user);
            }
        }
        // 如果订单状态都是完成状态，但金额发生变化
        else if (oldOrder.getOrderStatus() == 1 && order.getOrderStatus() == 1 
                && oldOrder.getOrderMoney() != null && order.getOrderMoney() != null
                && !oldOrder.getOrderMoney().equals(order.getOrderMoney())) {
            User user = userService.getById(order.getUserId());
            if (user != null) {
                // 计算金额差值
                BigDecimal amountDiff = order.getOrderMoney().subtract(oldOrder.getOrderMoney());
                // 更新用户余额
                BigDecimal newUserMoney = user.getUserMoney().add(amountDiff);
                user.setUserMoney(newUserMoney);
                userService.updateById(user);
            }
        }

        return updateById(order);
    }

    @Override
    @Transactional
    public boolean saveOrder(Order order) {
        boolean success = save(order);
        // 只有订单状态为已完成(1)时才增加用户余额
        if (success && order.getOrderStatus() == 1 && order.getOrderMoney() != null) {
            // 更新用户余额
            User user = userService.getById(order.getUserId());
            if (user != null) {
                BigDecimal newUserMoney = user.getUserMoney().add(order.getOrderMoney());
                user.setUserMoney(newUserMoney);
                userService.updateById(user);
            }
        }
        return success;
    }

}




